package com.sqx.modules.app.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.BlockAndUserDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.BlockAndUser;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.response.HomeMessageResponse;
import com.sqx.modules.app.response.UserMessageResponse;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.sign.dao.GoldRecordsDao;
import com.sqx.modules.sign.entity.GoldRecords;
import com.sqx.modules.sys.controller.AbstractController;
import io.jsonwebtoken.lang.Objects;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author fang
 * @date 2020/7/30
 */
@RestController
@Api(value = "用户管理", tags = {"用户管理"})
@RequestMapping(value = "/user")
public class UserController extends AbstractController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private PayDetailsService payDetailsService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private BlockAndUserDao blockAndUserDao;
    @Autowired
    private GoldRecordsDao goldRecordsDao;


    @RequestMapping(value = "/selectUserByInvitationCode", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserByInvitationCode(@ApiParam(value = "邀请码") String invitationCode) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userService.queryByInvitationCode(invitationCode);
        Long userId = userEntity.getUserId();
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        Double money = 0.0;
        if (userMoney != null) {
            money = userMoney.getMoney().doubleValue();
        }
        //查询用户钱包
        Double m = money;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        //查询本月充值
        Double consume = payDetailsService.instantselectSumPay(date, userId);
        //查询本月提现
        Double income = userMoneyDetailsService.monthIncome(date, userId);
        map.put("userEntity", userEntity);
        map.put("money", m);
        map.put("consume", consume);
        map.put("income", income);
        return Result.success().put("data", map);
    }


    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@ApiParam(value = "用户id") @PathVariable Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userService.queryByUserId(userId);
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        Double money = 0.0;
        if (userMoney != null) {
            money = userMoney.getMoney().doubleValue();
        }
        //查询用户钱包
        Double m = money;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        //查询本月充值
        Double consume = payDetailsService.instantselectSumPay(date, userId);
        //查询本月提现
        Double income = userMoneyDetailsService.monthIncome(date, userId);

        map.put("userEntity", userEntity);
        map.put("money", m);
        map.put("consume", consume);
        map.put("income", income);
       /* map.put("takeOrdersCount", takeOrdersCount);
        map.put("myOrdersCount", myOrdersCount);*/
        return Result.success().put("data", map);
    }

    @RequestMapping(value = "/addCannotMoney/{userId}/{money}/{type}", method = RequestMethod.POST)
    @ApiOperation("修改金额")
    @ResponseBody
    public Result addCannotMoney(@ApiParam(value = "用户id") @PathVariable("userId") Long userId,
                                 @ApiParam(value = "金额") @PathVariable("money") Double money,
                                 @ApiParam(value = "1增加 2减少") @PathVariable("type") Integer type) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        if (type == 1) {
//            userMoneyService.updateMoney(1, userId, money);
            UserEntity userEntity = userDao.selectById(userId);
            userEntity.setBalance(userEntity.getBalance().add(BigDecimal.valueOf(money)));
            userService.updateById(userEntity);
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("系统充值：" + money);
            userMoneyDetails.setTitle("系统充值金额");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(0);
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsService.save(userMoneyDetails);
            PayDetails payDetails = new PayDetails();
            payDetails.setState(1);
            payDetails.setCreateTime(format);
            payDetails.setOrderId("系统充值金额");
            payDetails.setUserId(userId);
            payDetails.setMoney(money);
            payDetails.setClassify(8);
            payDetails.setType(5);
            payDetailsService.save(payDetails);
        } else {
//            userMoneyService.updateMoney(2, userId, money);
            UserEntity userEntity = userDao.selectById(userId);
            if (userEntity.getBalance().doubleValue() >= money) {
                userEntity.setBalance(userEntity.getBalance().subtract(BigDecimal.valueOf(money)));
            }
            userService.updateById(userEntity);
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("系统减少：" + money);
            userMoneyDetails.setTitle("系统减少金额");
            userMoneyDetails.setType(2);
            userMoneyDetails.setClassify(0);
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsService.save(userMoneyDetails);
            PayDetails payDetails = new PayDetails();
            payDetails.setState(1);
            payDetails.setCreateTime(format);
            payDetails.setOrderId("系统减少金额");
            payDetails.setUserId(userId);
            payDetails.setMoney(money);
            payDetails.setClassify(8);
            payDetailsService.save(payDetails);
        }
        return Result.success();
    }


    @RequestMapping(value = "/selectUserList", method = RequestMethod.GET)
    @ApiOperation("查询所有用户列表")
    @ResponseBody
    public Result selectUserList(@ApiParam(value = "页码") Integer page,
                                 @ApiParam(value = "条数") Integer limit,
                                 @ApiParam(value = "开始时间") String startTime,
                                 @ApiParam(value = "结束时间") String endTime,
                                 @ApiParam(value = "用户") UserEntity userEntity) {
        return Result.success().put("data", userService.selectUserPage(page, limit, startTime, endTime, userEntity));
    }

    @RequestMapping(value = "/selectRecycleUserList", method = RequestMethod.GET)
    @ApiOperation("查询所有回收人员列表")
    @ResponseBody
    public Result selectRecycleUserList(@ApiParam(value = "页码") Integer page,
                                        @ApiParam(value = "条数") Integer limit) {
        Page<UserEntity> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return Result.success().put("data", userDao.selectPage(pages, new QueryWrapper<UserEntity>().eq("recycle_status", 1)));
    }


    @RequestMapping(value = "/deleteUserByUserId/{userId}", method = RequestMethod.POST)
    @ApiOperation("删除用户")
    @ResponseBody
    public Result deleteUserByUserId(@ApiParam(value = "用户id") @PathVariable("userId") Long userId) {
        userService.removeById(userId);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserByUserId", method = RequestMethod.POST)
    @ApiOperation("修改用户")
    @ResponseBody
    public Result updateUserByUserId(@RequestBody UserEntity userEntity) {
        UserEntity userEntity1 = userService.selectUserById(userEntity.getUserId());
        if (StringUtils.isNotBlank(userEntity.getPhone())) {
            if (!userEntity1.getPhone().equals(userEntity.getPhone())) {
                int phone = userService.count(new QueryWrapper<UserEntity>().eq("phone", userEntity.getPhone()));
                if (phone > 0) {
                    return Result.error("当前手机号已被注册！");
                }
            }
        }
        userService.updateById(userEntity);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserByCreditScore", method = RequestMethod.POST)
    @ApiOperation("修改用户信用分")
    @ResponseBody
    public Result updateUserByCreditScore(@RequestBody UserEntity userEntity) {
        UserEntity userEntity1 = userService.selectUserById(userEntity.getUserId());
        if (ObjectUtil.isNotEmpty(userEntity1)) {
            if (userEntity.getType() == 1) {
                if (userEntity.getCreditScore() >= 0 && userEntity.getCreditScore() <= 100) {
                    userEntity.setCreditScore(userEntity1.getCreditScore() + userEntity.getCreditScore());
                    if (userEntity.getCreditScore() > 100) {
                        return Result.error("信用分不能超过100");
                    }
                    userService.updateById(userEntity);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(userEntity.getUserId());
                    userMoneyDetails.setTitle("信用分增加");
                    UserEntity user = userService.selectUserById(userEntity.getUserId());
                    userMoneyDetails.setContent("信用分增加后总分:" + user.getCreditScore() + ",信用分增加：" + userEntity.getCreditScore());
                    userMoneyDetails.setType(userEntity.getType());
                    userMoneyDetails.setClassify(5);
                    userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    userMoneyDetailsService.save(userMoneyDetails);
                }
            } else {
                if (userEntity.getCreditScore() > 0 && userEntity.getCreditScore() <= 100) {
                    userEntity.setCreditScore(userEntity1.getCreditScore() - userEntity.getCreditScore());
                    if (userEntity.getCreditScore() < 0) {
                        return Result.error("信用分不能小于0");
                    }
                    userService.updateById(userEntity);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(userEntity.getUserId());
                    userMoneyDetails.setTitle("信用分减少");
                    UserEntity user = userService.selectUserById(userEntity.getUserId());
                    userMoneyDetails.setContent("信用分减少后总分:" + user.getCreditScore() + ",信用分减少：" + userEntity.getCreditScore());
                    userMoneyDetails.setClassify(5);
                    userMoneyDetails.setType(userEntity.getType());
                    userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    userMoneyDetailsService.save(userMoneyDetails);
                }
            }
        }
        userService.updateById(userEntity);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserByGold", method = RequestMethod.POST)
    @ApiOperation("修改用户金币")
    @ResponseBody
    public Result updateUserByGold(@RequestBody UserEntity userEntity) {
        UserEntity userEntity1 = userService.selectUserById(userEntity.getUserId());
        if (ObjectUtil.isNotEmpty(userEntity1)) {
            if (userEntity.getType() == 1) {
                userEntity.setTotalGold(userEntity1.getTotalGold() + userEntity.getTotalGold());
                userService.updateById(userEntity);
                GoldRecords goldRecords = new GoldRecords();
                goldRecords.setGoldChange(1);
                goldRecords.setGoldCoins(userEntity.getTotalGold());
                goldRecords.setRemark("后台操作");
                goldRecords.setUserId(userEntity.getUserId());
                goldRecords.setCreateTime(new Date());
                goldRecordsDao.insert(goldRecords);
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(userEntity.getUserId());
                userMoneyDetails.setTitle("金币增加");
                UserEntity user = userService.selectUserById(userEntity.getUserId());
                userMoneyDetails.setContent("金币增加后总金币数:" + user.getTotalGold() + "，金币增加：" + userEntity.getTotalGold());
                userMoneyDetails.setType(userEntity.getType());
                userMoneyDetails.setClassify(6);
                userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            } else {
                userEntity.setTotalGold(userEntity1.getTotalGold() - userEntity.getTotalGold());
                if (userEntity.getTotalGold() < 0) {
                    userEntity.setTotalGold(0);
                }
                userService.updateById(userEntity);
                GoldRecords goldRecords = new GoldRecords();
                goldRecords.setGoldChange(2);
                goldRecords.setGoldCoins(userEntity.getTotalGold());
                goldRecords.setRemark("后台操作");
                goldRecords.setUserId(userEntity.getUserId());
                goldRecords.setCreateTime(new Date());
                goldRecordsDao.insert(goldRecords);
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(userEntity.getUserId());
                userMoneyDetails.setTitle("金币减少");
                UserEntity user = userService.selectUserById(userEntity.getUserId());
                userMoneyDetails.setContent("金币减少后总金币数:" + user.getTotalGold() + "，金币减少：" + userEntity.getTotalGold());
                userMoneyDetails.setClassify(6);
                userMoneyDetails.setType(userEntity.getType());
                userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }
        }
        userService.updateById(userEntity);
        return Result.success();
    }


    @RequestMapping(value = "/updateUserStatusByUserId", method = RequestMethod.GET)
    @ApiOperation("禁用或启用用户")
    @ResponseBody
    public Result updateUserByUserId(@ApiParam(value = "用户id") Long userId) {
        UserEntity byId = userService.getById(userId);
        if (byId.getStatus().equals(1)) {
            byId.setStatus(2);
        } else {
            byId.setStatus(1);
        }
        userService.updateById(byId);
        return Result.success();
    }


    /**
     * 获取openid
     *
     * @param code 微信code
     * @return openid
     */
    @GetMapping("/openId/{code:.+}/{userId}")
    @ApiOperation("根据code获取openid")
    public Result getOpenid(@ApiParam(value = "微信请求code") @PathVariable("code") String code, @ApiParam(value = "用户id") @PathVariable(value = "userId") Long userId) {
        return userService.getOpenId(code, userId);
    }

    /**
     * 信息分析
     *
     * @return
     */
    @GetMapping("/homeMessage")
    @ApiOperation("信息分析")
    public Result homeMessage() {
        HomeMessageResponse homeMessageResponse = new HomeMessageResponse();
        //   0查总   1查天  2查月  3查年
        //设置总用户人数
        homeMessageResponse.setTotalUsers(userService.queryUserCount(0, null));
        //设置今日新增
        homeMessageResponse.setNewToday(userService.queryUserCount(1, null));
        //设置本月新增
        homeMessageResponse.setNewMonth(userService.queryUserCount(2, null));
        //设置本年新增
        homeMessageResponse.setNewYear(userService.queryUserCount(3, null));

        //设置总收入
        homeMessageResponse.setTotalRevenue(userService.queryPayMoney(0));
        //设置今日收入
        homeMessageResponse.setTodayRevenue(userService.queryPayMoney(1));
        //设置本月收入
        homeMessageResponse.setMonthRevenue(userService.queryPayMoney(2));
        //设置本年收入
        homeMessageResponse.setYearRevenue(userService.queryPayMoney(3));

        return Result.success().put("data", homeMessageResponse);
    }


    /**
     * 用户分析
     */
    @GetMapping("/userMessage")
    @ApiOperation("用户分析")
    public Result userMessage(@ApiParam(value = "日期") String date,
                              @ApiParam(value = "type筛选：1年月日 2年月 3年") int type) {
        UserMessageResponse userMessageResponse = new UserMessageResponse();
        // 总用户
        userMessageResponse.setTotalNumber(userService.queryUserCount(type, date));
//        userMessageResponse.setVipUserNumber(userService.userMessage(date, type));
//        userMessageResponse.setUserNumber(userService.queryUserCount(type, date) - userService.userMessage(date, type));
        // 小程序用户
        userMessageResponse.setWxUserNumber(userService.queryWxUserNumber(type, date));
        // app用户
        userMessageResponse.setAppUserNumber(userService.queryAppUserNumber(type, date));
        // h5用户
        userMessageResponse.setH5UserNumber(userService.queryH5UserNumber(type, date));
        // 公众号用户
        userMessageResponse.setPublicUserNumber(userService.queryPublicUserNumber(type, date));
        return Result.success().put("data", userMessageResponse);
    }

    /**
     * 用户分析
     */
    @GetMapping("/payMessage")
    @ApiOperation("充值统计")
    public Result payMessage(@ApiParam(value = "日期") String date,
                             @ApiParam(value = "type筛选：1年月日 2年月 3年") Integer type) {
        return Result.success().put("data", payDetailsService.payMessage(date, type));
    }

    @ApiOperation("查看自己拉黑用户的列表")
    @GetMapping("/selectBlackAllList")
    public Result selectBlacklist(@ApiParam(value = "页码") Integer page,
                                  @ApiParam(value = "条数") Integer limit,
                                  UserEntity user) {
        IPage<BlockAndUser> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<BlockAndUser> blockAndUserIPage = blockAndUserDao.selectAllList(pages, user);
        return Result.success().put("data", blockAndUserIPage);
    }

    @ApiOperation("订单统计")
    @GetMapping("/orderMessageCount")
    public Result orderMessageCount(@ApiParam(value = "日期") String date,
                                    @ApiParam(value = "type筛选：1年月日 2年月 3年") Integer type) {
        return Result.success().put("data", userService.orderMessageCount(date, type));
    }

    @ApiOperation("收入分析")
    @GetMapping("/incomeStatistics")
    public Result incomeStatistics(@ApiParam(value = "日期") String date,
                                    @ApiParam(value = "type筛选：1年月日 2年月 3年") Integer type) {
        return Result.success().put("data", userService.incomeStatistics(date, type));
    }

    @GetMapping("/selectUserCountStatisticsByTime")
    @ApiOperation("用户统计")
    public Result selectUserCountStatisticsByTime(String startTime, String endTime) {
        List<Integer> userCountList = new ArrayList<>();
        List<String> year = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(parse);
        while (true) {
            String dateTime = simpleDateFormat.format(calendar.getTime());
//            int i = userService.queryUserCount(1, dateTime,null,null);
            int i = userService.queryUserCount(1, dateTime);
            userCountList.add(i);
            year.add(dateTime);
            if (dateTime.equals(endTime)) {
                break;
            }
            calendar.add(Calendar.DATE, 1);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("userCountList", userCountList);
        result.put("year", year);
        return Result.success().put("data", result);
    }
}